<script lang="ts" setup>
import type { ShopGoodsApi } from '#/api/shop/goods';

import { computed, reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { getGoodsPage } from '#/api/shop/goods';
import { $t } from '#/locales';

interface CartItem extends ShopGoodsApi.Goods {
  quantity: number;
}

const emit = defineEmits<{
  success: [];
}>();

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    handleSubmit();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      // 获取手牌信息
      const data = modalApi.getData();
      if (data?.handCardInfo) {
        handCardInfo.value = data.handCardInfo;
      }
      init();
    }
  },
});

// 手牌信息
const handCardInfo = ref<any>(null);

// 计算弹窗标题
const modalTitle = computed(() => {
  if (handCardInfo.value) {
    const cardNumber =
      handCardInfo.value.cardNumber || handCardInfo.value.id || '未知';
    return `${$t('spa.handCard.consume')} - ${$t('spa.handCard.handCardNumber')}: ${cardNumber}`;
  }
  return $t('spa.handCard.consume');
});

// 商品列表相关
const goodsList = ref<ShopGoodsApi.Goods[]>([]);
const goodsLoading = ref(false);
const searchForm = reactive({
  goods_name: '',
  goods_type: '',
  brand_id: undefined,
  label_ids: '',
  start_sale_num: undefined,
  end_sale_num: undefined,
  start_price: undefined,
  end_price: undefined,
  status: 1,
  order: '',
  sort: '',
  // 新增搜索条件
  sub_title: '',
  site_id: undefined,
  is_gift: undefined,
});

const goodsPagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 购物车相关
const cartList = ref<CartItem[]>([]);

// 商品列表列配置
const goodsColumns = [
  {
    title: $t('spa.handCard.goodsImage'),
    dataIndex: 'goods_cover_thumb_small',
    key: 'goods_cover_thumb_small',
    width: 80,
  },
  {
    title: $t('spa.handCard.goodsName'),
    dataIndex: 'goods_name',
    key: 'goods_name',
    ellipsis: true,
  },
  {
    title: $t('spa.handCard.goodsType'),
    dataIndex: 'goods_type_name',
    key: 'goods_type_name',
  },
  {
    title: $t('spa.handCard.price'),
    dataIndex: 'goodsSku',
    key: 'price',
    width: 100,
  },
  {
    title: $t('spa.handCard.stock'),
    dataIndex: 'stock',
    key: 'stock',
    width: 80,
  },
  {
    title: $t('common.action'),
    key: 'action',
    width: 100,
  },
];

// 购物车列配置
const cartColumns = [
  {
    title: $t('spa.handCard.goodsName'),
    dataIndex: 'goods_name',
    key: 'goods_name',
    ellipsis: true,
  },
  {
    title: $t('spa.handCard.price'),
    dataIndex: 'goodsSku',
    key: 'price',
    width: 100,
  },
  {
    title: $t('spa.handCard.quantity'),
    dataIndex: 'quantity',
    key: 'quantity',
    width: 120,
  },
  {
    title: $t('spa.handCard.total'),
    key: 'total',
    width: 100,
  },
  {
    title: $t('common.action'),
    key: 'action',
    width: 80,
  },
];

// 计算总金额
const totalAmount = computed(() => {
  return cartList.value.reduce((total, item) => {
    return total + item.goodsSku.price * item.quantity;
  }, 0);
});

// 获取商品列表
async function fetchGoodsList() {
  goodsLoading.value = true;
  try {
    const params = {
      page: goodsPagination.current,
      limit: goodsPagination.pageSize,
      ...searchForm,
    };

    const response = await getGoodsPage(params);
    console.log('API Response:', response);
    // shopRequestClient 已经返回了 data 字段，所以 response 就是后端返回的 data 部分
    const data = response?.data;
    goodsList.value = Array.isArray(data) ? data : [];
    goodsPagination.total = response?.total || 0;
    console.log('Goods List:', goodsList.value);
  } catch {
    message.error('获取商品列表失败');
  } finally {
    goodsLoading.value = false;
  }
}

// 搜索商品
function handleSearch() {
  goodsPagination.current = 1;
  fetchGoodsList();
}

// 重置搜索条件
function handleReset() {
  Object.assign(searchForm, {
    goods_name: '',
    goods_type: '',
    brand_id: undefined,
    label_ids: '',
    start_sale_num: undefined,
    end_sale_num: undefined,
    start_price: undefined,
    end_price: undefined,
    status: 1,
    order: '',
    sort: '',
    sub_title: '',
    site_id: undefined,
    is_gift: undefined,
  });
  handleSearch();
}

// 表格变化处理
function handleTableChange(pagination: any) {
  goodsPagination.current = pagination.current;
  goodsPagination.pageSize = pagination.pageSize;
  fetchGoodsList();
}

// 添加到购物车
function handleAddToCart(goods: ShopGoodsApi.Goods) {
  const existingItem = cartList.value.find(
    (item) => item.goods_id === goods.goods_id,
  );

  if (existingItem) {
    if (existingItem.quantity >= (goods.stock || 0)) {
      message.warning('库存不足');
      return;
    }
    existingItem.quantity += 1;
  } else {
    cartList.value.push({
      ...goods,
      quantity: 1,
    });
  }

  message.success('已添加到购物车');
}

// 从购物车移除
function handleRemoveFromCart(goodsId: number) {
  const index = cartList.value.findIndex((item) => item.goods_id === goodsId);
  if (index !== -1) {
    cartList.value.splice(index, 1);
  }
}

// 修改数量
function handleQuantityChange(item: CartItem) {
  if (item.quantity <= 0) {
    item.quantity = 1;
  }
  if (item.quantity > (item.stock || 0)) {
    item.quantity = item.stock || 0;
    message.warning('数量不能超过库存');
  }
}

// 清空购物车
function handleClearCart() {
  cartList.value = [];
}

// 提交消费
async function handleSubmit() {
  if (cartList.value.length === 0) {
    message.warning('请选择要消费的商品');
    return false;
  }

  // 这里可以调用消费API
  // console.log('消费商品:', cartList.value);
  // console.log('总金额:', totalAmount.value);

  message.success('消费成功');
  emit('success');
  await modalApi.close();
  return true;
}

// 获取图片URL
function getImageUrl(imagePath: string) {
  if (!imagePath) return '';
  return `/shop-img-api/${imagePath}`;
}

// 初始化
function init() {
  fetchGoodsList();
}
</script>

<template>
  <Modal
    :title="modalTitle"
    :min-height="600"
    class="w-3/4"
    :style="{ top: '20px' }"
  >
    <div class="consume-modal">
      <!-- 商品列表区域 -->
      <div class="goods-section">
        <div class="section-header">
          <h3>{{ $t('spa.handCard.goodsList') }}</h3>
          <div class="search-bar">
            <a-row :gutter="[16, 8]">
              <a-col :span="6">
                <a-input
                  v-model:value="searchForm.goods_name"
                  :placeholder="$t('spa.handCard.goodsName')"
                  @press-enter="handleSearch"
                />
              </a-col>
              <a-col :span="6">
                <a-input
                  v-model:value="searchForm.sub_title"
                  :placeholder="$t('spa.handCard.subTitle')"
                  @press-enter="handleSearch"
                />
              </a-col>
              <a-col :span="6">
                <a-select
                  v-model:value="searchForm.goods_type"
                  :placeholder="$t('spa.handCard.goodsType')"
                  allow-clear
                  style="width: 100%"
                >
                  <a-select-option value="virtual">
                    {{ $t('spa.handCard.virtualGoods') }}
                  </a-select-option>
                  <a-select-option value="physical">
                    {{ $t('spa.handCard.physicalGoods') }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-select
                  v-model:value="searchForm.status"
                  :placeholder="$t('spa.handCard.status')"
                  style="width: 100%"
                >
                  <a-select-option :value="1">
                    {{ $t('spa.handCard.enabled') }}
                  </a-select-option>
                  <a-select-option :value="0">
                    {{ $t('spa.handCard.disabled') }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-input-number
                  v-model:value="searchForm.start_price"
                  :placeholder="$t('spa.handCard.minPrice')"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                />
              </a-col>
              <a-col :span="6">
                <a-input-number
                  v-model:value="searchForm.end_price"
                  :placeholder="$t('spa.handCard.maxPrice')"
                  :min="0"
                  :precision="2"
                  style="width: 100%"
                />
              </a-col>
              <a-col :span="6">
                <a-input-number
                  v-model:value="searchForm.start_sale_num"
                  :placeholder="$t('spa.handCard.minSales')"
                  :min="0"
                  style="width: 100%"
                />
              </a-col>
              <a-col :span="6">
                <a-input-number
                  v-model:value="searchForm.end_sale_num"
                  :placeholder="$t('spa.handCard.maxSales')"
                  :min="0"
                  style="width: 100%"
                />
              </a-col>
              <a-col :span="12">
                <a-space>
                  <a-button type="primary" @click="handleSearch">
                    {{ $t('common.search') }}
                  </a-button>
                  <a-button @click="handleReset">
                    {{ $t('spa.handCard.reset') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </div>
        </div>

        <a-table
          :columns="goodsColumns"
          :data-source="goodsList"
          :loading="goodsLoading"
          :pagination="goodsPagination"
          row-key="goods_id"
          size="small"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'goods_cover_thumb_small'">
              <a-image
                v-if="record.goods_cover_thumb_small"
                :src="getImageUrl(record.goods_cover_thumb_small)"
                :width="40"
                :height="40"
                :preview="false"
              />
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'price'">
              ¥{{ record.goodsSku?.price?.toFixed(2) }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-button
                type="primary"
                size="small"
                :disabled="!record.stock || record.stock <= 0"
                @click="handleAddToCart(record)"
              >
                {{ $t('spa.handCard.addToCart') }}
              </a-button>
            </template>
          </template>
        </a-table>
      </div>

      <!-- 购物车区域 -->
      <div class="cart-section">
        <div class="section-header">
          <h3>{{ $t('spa.handCard.shoppingCart') }}</h3>
          <a-button type="link" danger @click="handleClearCart">
            {{ $t('spa.handCard.clearCart') }}
          </a-button>
        </div>

        <div class="cart-content">
          <a-table
            :columns="cartColumns"
            :data-source="cartList"
            :pagination="false"
            row-key="goods_id"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'price'">
                ¥{{ record.goodsSku?.price?.toFixed(2) }}
              </template>
              <template v-else-if="column.key === 'total'">
                ¥{{ (record.goodsSku?.price * record.quantity).toFixed(2) }}
              </template>
              <template v-else-if="column.key === 'quantity'">
                <a-input-number
                  v-model:value="record.quantity"
                  :min="1"
                  :max="record.stock"
                  size="small"
                  style="width: 80px"
                  @change="handleQuantityChange(record)"
                />
              </template>
              <template v-else-if="column.key === 'action'">
                <a-button
                  type="link"
                  danger
                  size="small"
                  @click="handleRemoveFromCart(record.goods_id)"
                >
                  {{ $t('common.delete') }}
                </a-button>
              </template>
            </template>
          </a-table>

          <div class="cart-summary">
            <div class="total-info">
              <span class="total-label"
                >{{ $t('spa.handCard.totalAmount') }}:</span
              >
              <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Modal>
</template>

<style lang="less" scoped>
.consume-modal {
  display: flex;
  gap: 16px;
  height: calc(100vh - 200px);
  min-height: 500px;

  .goods-section {
    flex: 1;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    padding: 16px;

    .section-header {
      margin-bottom: 16px;

      h3 {
        margin: 0 0 16px 0;
        font-size: 16px;
        font-weight: 500;
      }

      .search-bar {
        .ant-row {
          margin-bottom: 8px;
        }
      }
    }
  }

  .cart-section {
    flex: 1;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    padding: 16px;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
      }
    }

    .cart-content {
      height: calc(100% - 60px);
      display: flex;
      flex-direction: column;

      .cart-summary {
        margin-top: 16px;
        padding-top: 16px;
        border-top: 1px solid #f0f0f0;

        .total-info {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .total-label {
            font-size: 16px;
            font-weight: 500;
          }

          .total-amount {
            font-size: 18px;
            font-weight: 600;
            color: #ff4d4f;
          }
        }
      }
    }
  }
}
</style>
